<!-- 商品列表 -->
<template>
	<view class="list-box" >
		<view class="head-box" v-if="!flag_big">
			<!-- 标题栏 -->
			<shopro-navbar>
				<view class="u-flex-1 u-flex u-col-center u-m-x-20" slot="content">
					<u-search placeholder="请输入关键字" @change="onSearch" @search="onSearch" @clear="clearSearch" v-model="searchVal" :showAction="false" height="60"></u-search>
				</view>
			</shopro-navbar>
			<!-- 筛选栏 -->
			<sh-filter @change="onFilter"></sh-filter>
		</view>
		
		<view class="head-box BIG-head" :style="{paddingTop:flag_big?'35px': '10px',position:flag_big?'fixed':'sticky'}" v-if="flag_big">
			<!-- 标题栏 -->
			<view :style="{display:flag_big?'flex':'block',padding:flag_big?'0 10px':'unset'}" class="head_box">
				<uni-icons @click="backFun" color="#000" class="icon-head" type="back" size="24"></uni-icons>
				<view class="search-BIG-box">
					
					<image class="searchIcon" :src="$IMG_URL+'/static/images/BIG-icon/search.png'" mode=""></image>
					<input type="text" v-model="searchVal" placeholder="搜索商品"
						placeholder-style="color: #666666;font-size: 13px;">
					<!-- <image class="yuyinIcon" style="width: 13px;height: 17px;" :src="$IMG_URL+'/static/images/index_top/yuyin.png'"
						mode=""></image> -->
				</view>
				<view class="search-BIG-btn" @click="keyWordFun">
					搜索
				</view>
			</view>
			<sh-filter @change="onFilter"></sh-filter>
			<!-- 筛选栏 -->
			<!-- <sh-filter @change="onFilter"></sh-filter> -->
		</view>

		<view class="head-box-BIG" v-else-if="flag_big">
			<uni-icons @click="backFun" class="icon-head" type="left" size="24"></uni-icons>	
			<text></text>
			<text>{{listName}}</text>
		</view>

		<view class="u-waterfall u-p-16" v-if="!isEmpty&!flag_big">
			<view id="u-left-column" class="u-column">
				<view class="goods-item u-m-b-16 u-flex u-row-center u-col-center" v-for="(leftGoods,irgggg) in leftList" :key="irgggg">
					<shopro-goods-card
						:detail="leftGoods"
						:type="leftGoods.activity_type"
						:image="leftGoods.image"
						:title="leftGoods.title"
						:subtitle="leftGoods.subtitle"
						:price="leftGoods.price"
						:originPrice="leftGoods.original_price"
						:sales="leftGoods.sales"
						:tagTextList="leftGoods.activity_discounts_tags"
						@click="$Router.push({ path: '/pages/goods/detail', query: { id: leftGoods.id } })"
					></shopro-goods-card>
				</view>
			</view>
			<view id="u-right-column" class="u-column">
				<view class="goods-item u-m-b-16 u-flex u-row-center u-col-center" v-for="(rightGoods,inddd) in rightList" :key="inddd">
					<shopro-goods-card
						:detail="rightGoods"
						:type="rightGoods.activity_type"
						:image="rightGoods.image"
						:title="rightGoods.title"
						:subtitle="rightGoods.subtitle"
						:price="rightGoods.price"
						:originPrice="rightGoods.original_price"
						:sales="rightGoods.sales"
						:tagTextList="rightGoods.activity_discounts_tags"
						@click="$Router.push({ path: '/pages/goods/detail', query: { id: rightGoods.id } })"
					></shopro-goods-card>
				</view>
			</view>
		</view>
		
		<view class="list-goods-BIG" :style="{paddingTop:flag_big?'115px':''}" v-else-if="!isEmpty&flag_big">
			<view class="cell-list-BIG" v-for="(item,index) in listBIG" :key="index" @click="$Router.push({ path: '/pages/goods/detail', query: { id: item.id } })">
				<view class="cell-list-BIG-l">
					<image :src="item.image" mode=""></image>
				</view>
				<view class="cell-list-BIG-r">
					<text class="goods-title">{{item.title}}</text>
					<view class="goods-price">
						￥<text>{{item.price}}</text>
					</view>
					<text class="goods-num">{{item.sales}}人已抢</text>
				</view>
			</view>
		</view>
		<!-- 缺省页 -->
		<shopro-empty v-if="isEmpty" :image="$IMG_URL + '/imgs/empty/empty_goods.png'" tipText="暂无该商品，还有更多好货等着你噢~"></shopro-empty>
		<!-- 加载更多 -->
		<u-loadmore v-show="!isEmpty" height="80rpx" :status="loadStatus" icon-type="flower" color="#ccc" />
		<!-- 登录弹窗 -->
		<shopro-auth-modal></shopro-auth-modal>
		<view v-if="flag_big" class="yuyinBOX" @touchstart="startRecording" @touchend="stopRecording">
			<image :src="$IMG_URL+'/static/images/index_top/yuyin.png'" mode=""></image>
			<text>按住说话搜一搜</text>
		</view>
		<view class="yuyinLoding" v-show="showyyLoding">
			<nest-jumping-spectrum :sWidth="500" :spectrumHeightMax="100" ref="jumpingSpectrum"></nest-jumping-spectrum>
		</view>
	</view>
</template>

<script>
import shFilter from './components/sh-filter.vue';
import { mapMutations, mapActions, mapState } from 'vuex';
const recorderManager = uni.getRecorderManager();
const innerAudioContext = uni.createInnerAudioContext();
let systemInfo = uni.getSystemInfoSync();
let historyTag = uni.getStorageSync('searchHistoryArr') ? JSON.parse(uni.getStorageSync('searchHistoryArr')) : [];
export default {
	components: {
		shFilter
	},
	computed:{
		// 是否为大字版
		flag_big(){
			return this.$store.state.user.isBIG
		}
	},
	data() {
		return {
			isEmpty: false,
			goodsList: [],
			searchVal: '',
			listParams: {
				category_id: 0,
				keywords: '',
				page: 1
			},
			loadStatus: 'loadmore', //loadmore-加载前的状态，loading-加载中的状态，nomore-没有更多的状态
			lastPage: 1,

			// 瀑布流 350-330
			addTime: 100, //排序间隙时间
			leftHeight: 0,
			rightHeight: 0,
			leftList: [],
			rightList: [],
			tempList: [],
			listBIG:[],
			listName:'',
			showyyLoding:false
		};
	},
	// 触底加载更多
	onReachBottom() {
		if (this.listParams.page < this.lastPage) {
			this.listParams.page += 1;
			this.getGoodsList();
		}
	},
	onLoad() {
		console.log(this.$Route.query);
		
		if (this.$Route.query.id) {
			this.listParams.category_id = this.$Route.query.id;
			try{
				this.listName = this.$Route.query.name
			}catch(e){
				console.log(e);
				//TODO handle the exception
			}
			this.getGoodsList();
		} else if (this.$Route.query.hasOwnProperty('keywords')) {
			this.listParams.keywords = this.$Route.query.keywords;
			this.searchVal = this.$Route.query.keywords;
			if(this.flag_big){
				this.getGoodsList();
			} else {
				!this.$Route.query.keywords && this.getGoodsList();
			}
			
		} else if (this.$Route.query.Bid){
			this.listParams.brand_id = this.$Route.query.Bid
			this.getGoodsList()
		}else {
			this.getGoodsList();
		}
		let self = this;
				recorderManager.onStop(function (res) {
					console.log('recorder stop' + JSON.stringify(res));
					// console.log(res);
					self.voicePath = res.tempFilePath;
					console.log(self.voicePath);
					// innerAudioContext.autoplay = true;
					innerAudioContext.src = self.voicePath;
					uni.uploadFile({
								url: 'https://xiaolao.edeapp.com/addons/shopro/asr.identify/index', //仅为示例，非真实的接口地址
								header: {
								    'token': self.$store.state.user.token
								  },
								filePath: self.voicePath,
								name: 'file',
								success: (uploadFileRes) => {
									// innerAudioContext.play()
									// console.log(uploadFileRes);
									console.log(uploadFileRes.data);
									let nData = JSON.parse(uploadFileRes.data)
									console.log(nData.data);
									// self.YYdata = uploadFileRes.data.data
									// self.$refs.headHome.inputEnter(nData)
									self.searchVal = nData.data
									self.keyWordFun()
								}
							});
				});
	},
	methods: {
		startRecording() {
					 this.showyyLoding = true
					 this.$refs.jumpingSpectrum.startJumping();
					 console.log('开始录音1');
					 
					 			// recorderManager.start({
		       //       format: 'wav',
		       //       // format: 'mp3',
							  // sampleRate:'32000',
							  // encodeBitRate:'108000',
		       //       success: (res) => {
		       //         console.log('开始录音2', res.tempFilePath);
		       //         // 可以在开始录音成功后进行一些操作，如更新状态或界面
		       //       },
		       //       fail: (err) => {
		       //         console.error('开始录音失败', err);
		       //       }
		       //     });
				   recorderManager.start({
				     format: 'wav',
				     // format: 'PCM',
				   			  // format:'pcm',
				     // format: 'mp3',
				   			  sampleRate:16000,
				   			  encodeBitRate:96000,
				   			  // frameSize:50,
				   			  numberOfChannels:1,
				   			  duration:60000,
				     success: (res) => {
				       console.log('开始录音2', res);
				       // 可以在开始录音成功后进行一些操作，如更新状态或界面
				     },
				     fail: (err) => {
				       console.error('开始录音失败', err);
				     }
				   });
		   },
		   stopRecording() {
						 this.showyyLoding = false
						 this.$refs.jumpingSpectrum.stopJumping();
					 console.log('录音结束');
					 			recorderManager.stop(res=>{
									console.log(res);
									this
								});
		   },
		// 瀑布流相关
		async splitData() {
			if (!this.tempList.length) return;
			let item = this.tempList[0];
			if (!item) return;

			// 分左右
			if (this.leftHeight < this.rightHeight) {
				this.leftHeight += item.activity_discounts_tags.length ? 350 : 330;
				this.leftList.push(item);
			} else if (this.leftHeight > this.rightHeight) {
				this.rightHeight += item.activity_discounts_tags.length ? 350 : 330;
				this.rightList.push(item);
			} else {
				this.leftHeight += item.activity_discounts_tags?.length ? 350 : 330;
				this.leftList.push(item);
			}

			// 移除临时列表的第一项，如果临时数组还有数据，继续循环
			this.tempList.splice(0, 1);
			if (this.tempList.length) {
				setTimeout(() => {
					this.splitData();
				}, this.addTime);
			}
		},
		clear() {
			this.leftList = [];
			this.rightList = [];
			this.leftHeight = 0;
			this.rightHeight = 0;
			this.tempList = [];
		},
		keyWordFun(){
			this.listParams.category_id = 0
			this.listParams.keywords = this.searchVal
			this.listParams.page = 1
			this.listParams.brand_id = ''
			this.listBIG = []
			this.getGoodsList()
		},
		backFun(){
			uni.navigateBack()
		},
		onFilter(e) {
			this.listParams.order = e;
			this.goodsList = [];
			this.listBIG=[]
			this.listParams.page = 1;
			this.lastPage = 1;
			this.clear();
			this.$u.debounce(this.getGoodsList);
		},
		// 键盘搜索,输入搜索
		onSearch() {
			this.goodsList = [];
			this.listParams.page = 1;
			this.lastPage = 1;
			this.listParams.keywords = this.searchVal;
			this.clear();
			this.$u.debounce(this.getGoodsList);
		},

		// 队列
		getArr(list, item) {
			let arr = list;
			let length = 10; //队列长度
			arr.length < length ? arr.unshift(item) : arr.pop();
			return arr;
		},

		// 清除搜索框
		clearSearch() {
			this.searchVal = '';
			this.clear();
		},
		// 商品列表
		getGoodsList() {
			let that = this;
			that.loadStatus = 'loading';
			if(!this.flag_big){
				that.$http('goods.lists', that.listParams, '加载中...').then(res => {
					  console.log('请求参数',that.listParams);
					console.log('商品列表',res);
					if (this.searchVal && !historyTag.includes(this.searchVal)) {
						let searchHistoryArr = JSON.stringify(this.getArr(historyTag, this.searchVal));
						uni.setStorageSync('searchHistoryArr', searchHistoryArr);
					}
					if (res.code === 1) {
						that.goodsList = [...that.goodsList, ...res.data.data];
						that.isEmpty = !that.goodsList.length;
						that.lastPage = res.data.last_page;
						that.loadStatus = that.listParams.page < res.data.last_page ? 'loadmore' : 'nomore';
						that.tempList = res.data.data;
						that.splitData();
					}
				});
				
				
			} else {
				that.$http('goods.lists', that.listParams).then(res=>{
					console.log('商品搜索结果',res);
					that.listBIG =  [...that.listBIG, ...res.data.data];
					that.lastPage = res.data.last_page;
					that.loadStatus = that.listParams.page < res.data.last_page ? 'loadmore' : 'nomore';
				})
			}
		
		}
	}
};
</script>

<style lang="scss">
	/*  #ifdef  MP-WEIXIN  */
	.BIG-head {
		padding-top: 85px !important;
	}
	.list-goods-BIG {
		padding-top: 165px !important;
	}
	/*  #endif  */
	.yuyinLoding {
		 height: 175rpx;
		        display: flex;
		        align-items: center;
		            position: fixed;
		            left: 50%;
		            transform: translateX(-50%);
		            justify-content: center;
		            bottom: 20%;
					background-color: rgb(137,217,97);
					border-radius: 15px;
					padding: 0 15px;
	}
	.yuyinBOX {
		position: fixed;
		left: 50%;
		bottom: 31px;
		transform: translateX(-50%);
		height: 47px;
			background-image: linear-gradient(0deg, 
				#ffd0bc 0%, 
				#ffe5da 100%), 
			linear-gradient(
				#ffd3c2, 
				#ffd3c2);
			background-blend-mode: normal, 
				normal;
			box-shadow: 0px 6px 18px 0px 
				rgba(0, 0, 0, 0.38);
			border-radius: 23px;
			border: solid 2px #ffffff;
			display: flex;
			align-items: center;
			justify-content: center;
				padding: 0 30px;
			image {
				width: 15px;
				height: 20px;
			}
			text {
				margin-left: 15px;
				font-size: 20px;
					font-weight: bold;
				white-space: nowrap;
				color: #ff3400;
			}
	}
	// page {
	// 	padding-top: 32px;
	// }
	.head_box {
		align-items: center;
		.search-BIG-box {
			display: flex;
			flex: 1;
			height: 34px;
				background-color: #ffffff;
				border-radius: 17px;
				border: solid 2px #e5e5e5;
				align-items: center;
				padding: 0 15px;
				box-sizing: border-box;
				input {
					flex: 1;
				}
				.searchIcon {
					width: 16px;
					height: 16px;
					margin-right: 9px;
				}
		}
		.search-BIG-btn {
			height: 34px;
				background-image: linear-gradient(90deg, 
					#ff8300 0%, 
					#ff3d00 100%), 
				linear-gradient(
					#ff4000, 
					#ff4000);
				background-blend-mode: normal, 
					normal;
				border-radius: 17px;
				padding: 11px 21px;
				box-sizing: border-box;
				display: flex;
				align-items: center;
				color: #fff;
				margin-left: 5px;
		}
	}
	
	.list-goods-BIG{
		padding:10px 5px ;
		box-sizing: border-box;
		.cell-list-BIG {
			background-color: #fff; 
			border-radius: 10px;
			margin-top: 10px;
			display: flex;
			.cell-list-BIG-l {
				display: flex;
				align-items: center;
				image{
					max-width: 168px;
					max-height: 167px;
						// background-color: #c9c4c4;
					border-radius: 10px;
				}
			}
			.cell-list-BIG-r {
				flex: 1;
				margin-left: 10px;
				display: flex;
				flex-direction: column;
				justify-content: space-between;
				padding-top: 9px;
				padding-bottom: 4px;
				box-sizing: border-box;
				// &:first-child {
				// 	margin-top: ;
				// }
				.goods-title {
					font-size: 22px;
					font-weight: bold;
					color: #000;
					overflow : hidden;
					text-overflow: ellipsis;
					display: -webkit-box;
					-webkit-line-clamp: 3;
					-webkit-box-orient: vertical;
				}
				.goods-price {
					flex: 1;
					display: flex;
					align-items: flex-end;
					color: #ff0000;
					font-weight: bold;
					font-size: 20px;
					text {
						font-size: 28px;
					}
				}
				.goods-num {
					color: #ff0000;
					font-size: 20px;
				}
			}
		}
	}
	
	.head-box-BIG {
		position: relative;
		// background-color: aqua;
		margin-top: 16px;
		.icon-head {
			position: absolute;
			left: 10px;
			// top: 0;
			bottom: 50%;
			transform: translateY(50%);
		}
		text {
			display: block;
			text-align: center;
			color: #010101;
			font-size: 20px;
			font-weight: bold;
			// margin-top: 39px;
		}
	}
	
@mixin vue-flex($direction: row) {
	/* #ifndef APP-NVUE */
	display: flex;
	flex-direction: $direction;
	/* #endif */
}
.u-waterfall {
	@include vue-flex;
	flex-direction: row;
	align-items: flex-start;
}

.u-column {
	@include vue-flex;
	flex: 1;
	flex-direction: column;
	height: auto;
}
.head-box {
	position: -webkit-sticky;
	position: sticky;
	top: 0;
	z-index: 998;
	background: #fff;
}
</style>
